/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.contract.contractinfo.web;

import java.util.Optional;
import cn.hutool.core.convert.Convert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.result.ResultWrapper;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.opsli.core.log.enums.*;
import org.opsli.core.log.annotation.OperateLogger;

import org.opsli.modulars.contract.contractinfo.entity.Contract;
import org.opsli.api.wrapper.contract.contractinfo.ContractModel;
import org.opsli.modulars.contract.contractinfo.service.IContractService;
import org.opsli.api.web.contract.contractinfo.ContractRestApi;

/**
 * 会员合同 Controller
 *
 * @author 17607080935
 * @date 2025-07-07 16:42:17
 */
@Api(tags = ContractRestApi.TITLE)
@Slf4j
@ApiRestController("/{ver}/contract/contractinfo")
public class ContractRestController extends BaseRestController<Contract, ContractModel, IContractService>
        implements ContractRestApi {

    /**
     * 会员合同 查一条
     * 
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得单条会员合同", notes = "获得单条会员合同 - ID")
    @PreAuthorize("hasAuthority('contract_contractinfo_select')")
    @Override
    public ResultWrapper<ContractModel> get(ContractModel model) {
        // 如果系统内部调用 则直接查数据库
        if (model != null && model.getIzApi() != null && model.getIzApi()) {
            model = IService.get(model);
        }
        return ResultWrapper.getSuccessResultWrapper(model);
    }

    /**
     * 会员合同 查询分页
     * 
     * @param pageNo   当前页
     * @param pageSize 每页条数
     * @param request  request
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @PreAuthorize("hasAuthority('contract_contractinfo_select')")
    @Override
    public ResultWrapper<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        QueryBuilder<Contract> queryBuilder = new WebQueryBuilder<>(IService.getEntityClass(),
                request.getParameterMap());
        Page<Contract, ContractModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultWrapper.getSuccessResultWrapper(page.getPageData());
    }

    /**
     * 会员合同 新增
     * 
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "新增会员合同数据", notes = "新增会员合同数据")
    @PreAuthorize("hasAuthority('contract_contractinfo_insert')")
    @OperateLogger(description = "新增会员合同数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> insert(ContractModel model) {
        // 调用新增方法
        IService.insert(model);
        return ResultWrapper.getSuccessResultWrapperByMsg("新增会员合同成功");
    }

    /**
     * 会员合同 修改
     * 
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "修改会员合同数据", notes = "修改会员合同数据")
    @PreAuthorize("hasAuthority('contract_contractinfo_update')")
    @OperateLogger(description = "修改会员合同数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @Override
    public ResultWrapper<?> update(ContractModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultWrapper.getSuccessResultWrapperByMsg("修改会员合同成功");
    }

    /**
     * 会员合同 删除
     * 
     * @param id ID
     * @return ResultVo
     */
    @ApiOperation(value = "删除会员合同数据", notes = "删除会员合同数据")
    @PreAuthorize("hasAuthority('contract_contractinfo_delete')")
    @OperateLogger(description = "删除会员合同数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> del(String id) {
        IService.delete(id);
        return ResultWrapper.getSuccessResultWrapperByMsg("删除会员合同成功");
    }

    /**
     * 会员合同 批量删除
     * 
     * @param ids ID 数组
     * @return ResultVo
     */
    @ApiOperation(value = "批量删除会员合同数据", notes = "批量删除会员合同数据")
    @PreAuthorize("hasAuthority('contract_contractinfo_delete')")
    @OperateLogger(description = "批量删除会员合同数据", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> delAll(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultWrapper.getSuccessResultWrapperByMsg("批量删除会员合同成功");
    }

    /**
     * 会员合同 Excel 导出认证
     *
     * @param type    类型
     * @param request request
     */
    @ApiOperation(value = "Excel 导出认证", notes = "Excel 导出认证")
    @PreAuthorize("hasAnyAuthority('contract_contractinfo_export', 'contract_contractinfo_import')")
    @Override
    public ResultWrapper<String> exportExcelAuth(String type, HttpServletRequest request) {
        Optional<String> certificateOptional = super.excelExportAuth(type, ContractRestApi.SUB_TITLE, request);
        if (!certificateOptional.isPresent()) {
            return ResultWrapper.getErrorResultWrapper();
        }
        return ResultWrapper.getSuccessResultWrapper(certificateOptional.get());
    }

    /**
     * 会员合同 Excel 导出
     * 
     * @param response response
     */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @PreAuthorize("hasAuthority('contract_contractinfo_export')")
    @OperateLogger(description = "会员合同 导出Excel", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.SELECT, db = true)
    @Override
    public void exportExcel(String certificate, HttpServletResponse response) {
        // 导出Excel
        super.excelExport(certificate, response);
    }

    /**
     * 会员合同 Excel 导入
     * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
     * 
     * @param request 文件流 request
     * @return ResultVo
     */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @PreAuthorize("hasAuthority('contract_contractinfo_import')")
    @OperateLogger(description = "会员合同 Excel 导入", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    // ======================= 审批相关接口 =======================

    /**
     * 提交合同审批
     * 
     * @param id 合同ID
     * @return ResultWrapper
     */
    @ApiOperation(value = "提交合同审批", notes = "提交合同审批")
    @PreAuthorize("hasAuthority('contract_contractinfo_approval')")
    @OperateLogger(description = "提交合同审批", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @PostMapping("/submitApproval/{id}")
    public ResultWrapper<?> submitApproval(@PathVariable("id") String id) {
        boolean result = IService.submitForApproval(id);
        if (result) {
            return ResultWrapper.getSuccessResultWrapperByMsg("提交审批成功");
        } else {
            return ResultWrapper.getErrorResultWrapper().setMsg("提交审批失败");
        }
    }

    /**
     * 获取合同审批状态
     * 
     * @param id 合同ID
     * @return ResultWrapper
     */
    @ApiOperation(value = "获取合同审批状态", notes = "获取合同审批状态")
    @PreAuthorize("hasAuthority('contract_contractinfo_select')")
    @GetMapping("/approvalStatus/{id}")
    public ResultWrapper<String> getApprovalStatus(@PathVariable("id") String id) {
        String status = IService.getApprovalStatus(id);
        return ResultWrapper.getSuccessResultWrapper(status);
    }

    /**
     * 审批通过回调
     * 
     * @param id 合同ID
     * @return ResultWrapper
     */
    @ApiOperation(value = "审批通过回调", notes = "审批通过回调")
    @PreAuthorize("hasAuthority('contract_contractinfo_approval')")
    @OperateLogger(description = "合同审批通过", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @PostMapping("/approvalApproved/{id}")
    public ResultWrapper<?> approvalApproved(@PathVariable("id") String id) {
        IService.onApprovalApproved(id);
        return ResultWrapper.getSuccessResultWrapperByMsg("处理审批通过成功");
    }

    /**
     * 审批拒绝回调
     * 
     * @param id 合同ID
     * @return ResultWrapper
     */
    @ApiOperation(value = "审批拒绝回调", notes = "审批拒绝回调")
    @PreAuthorize("hasAuthority('contract_contractinfo_approval')")
    @OperateLogger(description = "合同审批拒绝", module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @PostMapping("/approvalRejected/{id}")
    public ResultWrapper<?> approvalRejected(@PathVariable("id") String id) {
        IService.onApprovalRejected(id);
        return ResultWrapper.getSuccessResultWrapperByMsg("处理审批拒绝成功");
    }

}